package org.example.mulitithreading.ex11;

public class Demo {
    static final Object objA = new Object();
    static final Object objB = new Object();

    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        new Thread(runnable, "线程A").start();
        new Thread(runnable, "线程B").start();
    }

    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            while (true) {
                if ("线程A".equals(Thread.currentThread().getName())) {
                    synchronized (objA) {
                        System.out.println("线程A拿到了A锁，准备拿B锁");
                        synchronized (objB) {
                            System.out.println("线程A拿到了B锁，顺利执行完一轮");
                        }
                    }
                } else if ("线程B".equals(Thread.currentThread().getName())) {
                    synchronized (objB) {
                        System.out.println("线程B拿到了B锁，准备拿A锁");
                        synchronized (objA) {
                            System.out.println("线程B拿到了A锁，顺利执行完一轮");
                        }
                    }
                }
            }
        }
    }
}
